package com.central.project.controller;

import com.central.common.annotation.LoginUser;
import com.central.common.annotation.RequiredPermission;
import com.central.common.constant.PermissionConstants;
import com.central.common.model.*;
import com.central.common.utils.UserRoleUtil;
import com.central.common.model.SysProject;
import com.central.common.model.ProUserRole;
import com.central.project.service.IProUserRoleService;
import com.central.project.service.ISysProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@RestController
@Api(tags = "项目模块api")
@Slf4j
@RequestMapping("/project")
public class SysProjectController {
    @Autowired
    private ISysProjectService projectService;
    @Autowired
    private IProUserRoleService proUserRoleService;

    /**
     * 添加项目
     *
     * @param project
     * @return
     */
    @ApiOperation(value = "添加项目")
    @PostMapping("create")
    @RequiredPermission({PermissionConstants.SYS_ADMIN})
    public Result create(@RequestBody SysProject project) {
        try {
            return projectService.create(project);
        } catch (Exception ex) {
            log.error("memu-saveOrUpdate-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "项目查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/findProjects")
    public PageResult<SysProject> findProjects(@ApiIgnore @LoginUser SysUser user, @RequestParam Map<String, Object> params) {
        if (UserRoleUtil.checkSysAdmin(user.getRoles())) {
            return projectService.findProjects(params);
        } else {
            return projectService.findUserProjects(user.getId(), params);
        }
    }

    @ApiOperation(value = "用户项目列表")
    @GetMapping("/findUserProjects")
    public List<SysProject> findUserProjects(Long userId) {
        Map<String, Object> params=new HashMap<>();
        params.put("page",1);
        params.put("limit",1000);
        return projectService.findUserProjects(userId, params).getData();
    }

    @ApiOperation(value = "获取单用户项目角色")
    @GetMapping("/findRolesByUserId")
    public List<ProUserRole> findRolesByUserId(Long proId, Long userId) {
        return proUserRoleService.findRolesByUserId(proId,userId);
    }

    @ApiOperation(value = "查询项目成员及角色")
    @GetMapping("/findRolesByProId")
    public List<ProUserRole> findRolesByProId(Long proId) {
        return proUserRoleService.findRolesByProId(proId);
    }

    @ApiOperation(value = "修改别名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "proId", value = "项目id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "项目名", required = true, dataType = "String")
    })
    @GetMapping("/updateAlias")
    @RequiredPermission({PermissionConstants.PRO_ADMIN})
    public Result updateAlias(@ApiIgnore @LoginUser SysUser user,Long proId, String alias) {
        if(!proId.equals(user.getCurrentProjectId())){
            return Result.failed("操作失败：当前项目与修改项目不匹配");
        }
        try {
            SysProject project = projectService.getById(proId);
            project.setAlias(alias);
            projectService.updateById(project);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("project-updateName-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "修改描述")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "proId", value = "项目id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "desc", value = "描述", required = true, dataType = "String")
    })
    @GetMapping("/updateDesc")
    @RequiredPermission(PermissionConstants.PRO_ADMIN)
    public Result updateDesc(@ApiIgnore @LoginUser SysUser user,Long proId, String desc) {
        if(!proId.equals(user.getCurrentProjectId())){
            return Result.failed("操作失败：当前项目与修改项目不匹配");
        }
        try {
            SysProject project = projectService.getById(proId);
            project.setDescription(desc);
            projectService.updateById(project);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("project-updateDesc-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "修改部门")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "proId", value = "项目id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "departmentId", value = "部门id", required = true, dataType = "Long")
    })
    @GetMapping("/updateDepartment")
    @RequiredPermission(PermissionConstants.SYS_ADMIN)
    public Result updateDepartment(Long proId, Long departmentId) {
        try {
            SysProject project = projectService.getById(proId);
            project.setDepartmentId(departmentId);
            projectService.updateById(project);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("project-updateDepartment", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "系统管理员修改项目管理员")
    @PostMapping("/updateProAdmins/{proId}")
    @RequiredPermission(PermissionConstants.SYS_ADMIN)
    public Result updateProAdmins(@PathVariable("proId") Long proId,@RequestBody Set<Long> userIds) {
        try {
            proUserRoleService.updateProAdmins(proId,userIds);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("project-editProAdmins-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "添加项目员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "proId", value = "proId", required = true, dataType = "Long"),
    })
    @GetMapping("/addProMenber")
    @RequiredPermission({PermissionConstants.PRO_ADMIN,PermissionConstants.SYS_ADMIN})
    public Result addProMenber(@ApiIgnore @LoginUser SysUser user,Long userId,Long proId) {
        try {
            if(UserRoleUtil.checkSysAdmin(user.getRoles())){
                return proUserRoleService.addProMenbers(proId,userId);
            }else if(proId.equals(user.getCurrentProjectId())){
                return proUserRoleService.addProMenbers(proId,userId);
            }else {
                return Result.failed("操作失败:当前项目与操作项目不匹配");
            }
        } catch (Exception ex) {
            log.error("project-addProMenber-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "移除项目员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "Long"),
    })
    @GetMapping("/delProMenber")
    @RequiredPermission(PermissionConstants.PRO_ADMIN)
    public Result delProMenber(@ApiIgnore @LoginUser SysUser user,Long userId) {
        try {
            return proUserRoleService.delProMenbers(user.getCurrentProjectId(),userId);
        } catch (Exception ex) {
            log.error("project-delProMenber-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "修改项目成员角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "proId", value = "proId", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "roles", value = "角色id集合", required = true, dataType = "Set<Long>"),
    })
    @PostMapping("/updateProMenberRole")
    @RequiredPermission({PermissionConstants.PRO_ADMIN,PermissionConstants.SYS_ADMIN})
    public Result updateProMenberRole(@ApiIgnore @LoginUser SysUser user,@RequestParam Long proId,@RequestParam Long userId,@RequestBody Set<Long> roles) {
        try {
            if(UserRoleUtil.checkSysAdmin(user.getRoles())){
                return proUserRoleService.updateProMenberRole(proId,userId,roles);
            }else if(proId.equals(user.getCurrentProjectId())){
                return proUserRoleService.updateProMenberRole(proId,userId,roles);
            }else {
                return Result.failed("操作失败:当前项目与操作项目不匹配");
            }
        } catch (Exception ex) {
            log.error("project-delProMenber-error", ex);
            return Result.failed("操作失败");
        }
    }


    @ApiOperation(value = "部门是否被项目引用")
    @GetMapping("/countByDepartmentId")
    public Integer countByDepartmentId(Long departmentId) {
        return projectService.countByDepartmentId(departmentId);
    }

    @ApiOperation(value = "根据项目ids获取项目")
    @PostMapping("/findProByProIds")
    public List<SysProject> findProByProIds(@RequestBody List<Long> proIds){
        return projectService.findProByProIds(proIds);
    }

    @ApiOperation(value = "项目名搜索列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "项目名", required = false, dataType = "String")
    })
    @GetMapping("/search")
    public List<SysProject> search(String name) {
        return projectService.selectLikeName(name);
    }

    @ApiOperation(value = "通过id获取项目信息")
    @GetMapping("/findById")
    public SysProject findById(Long proId) {
        return projectService.getById(proId);
    }

}
